package com.gitee.dolt.utils.excel.importd;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.gitee.dolt.utils.excel.PoiUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;

/**
 * @author LYH
 */
@Slf4j
public abstract class BaseExcelImportHandler {

    public final ExcelImportResult importFile(File file) {
        return importFile(file, Collections.emptyMap());
    }

    public final ExcelImportResult importFile(File file, Map<String, Object> params) {
        try (ExcelReader reader = ExcelUtil.getReader(file)) {
            if (!checkHeader(reader)) {
                return new ExcelImportResult()
                        .setSuccess(false)
                        .setMessage(StrUtil.format("表头不匹配。{}", Arrays.toString(headerText())));
            }
            return doImport(reader, params);
        }
    }

    protected boolean checkHeader(ExcelReader reader) {
        String[] headerText = headerText();
        Row headerRow = reader.getOrCreateRow(0);
        for (int i = 0; i < headerText.length; i++) {
            String val = PoiUtils.getCellValue(headerRow, i, String.class);
            if (!headerText[i].equals(val)) {
                return false;
            }
        }
        return true;
    }

    protected String[] headerText() {
        return new String[]{};
    }

    protected abstract ExcelImportResult doImport(ExcelReader reader, Map<String, Object> params);


}
